package com.tang.bloghandle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.bloghandle.dto.BlogInfoDto;
import com.tang.bloghandle.dto.PageBlogDto;
import com.tang.bloghandle.entity.BlogEntity;
import com.tang.bloghandle.entity.BlogImageEntity;
import com.tang.bloghandle.entity.DictEntity;
import com.tang.bloghandle.mapper.BlogMapper;
import com.tang.bloghandle.service.IBlogImageService;
import com.tang.bloghandle.service.IBlogService;
import com.tang.bloghandle.service.IDictService;
import com.tang.bloghandle.vo.BlogInfoVo;
import com.tang.common.feign.FileCenterFeign;
import com.tang.common.feign.UserCenterFeign;
import com.tang.common.utils.UserUtils;
import com.tang.common.vo.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客 服务实现类
 * </p>
 *
 * @author tang.shencai
 * @since 2024-08-17
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, BlogEntity> implements IBlogService {
    @Resource
    private IDictService dictService;
    @Resource
    private UserCenterFeign userCenterFeign;
    @Resource
    private IBlogImageService blogImageService;
    @Resource
    private FileCenterFeign fileCenterFeign;


    @Override
    public Page<BlogInfoVo> pageCatalog(PageBlogDto dto) {
        Page<BlogEntity> page = page(new Page<>(dto.getCurrent(), dto.getSize()), new LambdaQueryWrapper<BlogEntity>()
                .select(BlogEntity::getId, BlogEntity::getTitle, BlogEntity::getCover, BlogEntity::getCreateTime, BlogEntity::getWriter)
                .like(StringUtils.isNotBlank(dto.getBlogTitle()), BlogEntity::getTitle, dto.getBlogTitle())
                .orderByDesc(BlogEntity::getCreateTime)
                .eq(BlogEntity::getIsRelease, 1));
        List<BlogInfoVo> collect = page.getRecords().stream().map(item -> {
            BlogInfoVo blogInfoVo = BeanUtil.copyProperties(item, BlogInfoVo.class);
            blogInfoVo.setUserEntity(userCenterFeign.getByUserName(item.getWriter()).getData());
            return blogInfoVo;
        }).collect(Collectors.toList());
        Page<BlogInfoVo> blogInfoVoPage = new Page<>();
        blogInfoVoPage.setRecords(collect);
        blogInfoVoPage.setTotal(page.getTotal());
        blogInfoVoPage.setCurrent(page.getCurrent());
        blogInfoVoPage.setSize(page.getSize());
        blogInfoVoPage.setPages(page.getPages());
        return blogInfoVoPage;
    }

    @Override
    public void replace(String oldStr, String newStr) {
        list().forEach(item -> {
            if (item.getContent().contains(oldStr)){
                update(new LambdaUpdateWrapper<BlogEntity>()
                        .set(BlogEntity::getContent,item.getContent().replace(oldStr,newStr))
                        .eq(BlogEntity::getId,item.getId()));
            }
        });
    }

    @Override
    public Page<BlogEntity> pageMyCatalog(PageBlogDto dto) {
        String currentUserName = UserUtils.getCurrentUserName();
        return page(new Page<>(dto.getCurrent(), dto.getSize()), new LambdaQueryWrapper<BlogEntity>()
                .select(BlogEntity::getId, BlogEntity::getTitle, BlogEntity::getCover, BlogEntity::getIsRelease, BlogEntity::getCreateTime, BlogEntity::getWriter)
                .like(StringUtils.isNotBlank(dto.getBlogTitle()), BlogEntity::getTitle, dto.getBlogTitle())
                .eq(BlogEntity::getWriter,currentUserName)
                .eq(BlogEntity::getDealFlag,0)
                .orderByDesc(BlogEntity::getCreateTime));
    }

    @Override
    public List<BlogEntity> getTopBlog() {
        List<String> collect = dictService.getDictList("SHOW_TOP_BLOG").stream().map(DictEntity::getValue).collect(Collectors.toList());
        return list(new LambdaQueryWrapper<BlogEntity>()
                .select(BlogEntity::getId, BlogEntity::getTitle, BlogEntity::getCover, BlogEntity::getCreateTime, BlogEntity::getWriter)
                .in(BlogEntity::getId,collect));
    }

    @Override
    public BlogInfoDto getCurrentUserBlogInfo() {
        return new BlogInfoDto(
                count(new LambdaQueryWrapper<BlogEntity>().eq(BlogEntity::getWriter, UserUtils.getCurrentUserName())),
                0L,
                0L);
    }

    @Override
    public void updateBlog(BlogEntity entity) {
        update(new LambdaUpdateWrapper<BlogEntity>()
                .set(StringUtils.isNotBlank(entity.getTitle()),BlogEntity::getTitle,entity.getTitle())
                .set(StringUtils.isNotBlank(entity.getContent()),BlogEntity::getContent,entity.getContent())
                .set(StringUtils.isNotBlank(entity.getCover()),BlogEntity::getCover,entity.getCover())
                .set(entity.getIsRelease() != null,BlogEntity::getIsRelease,entity.getIsRelease())
                .set(entity.getDealFlag() != null,BlogEntity::getDealFlag,entity.getDealFlag())
                .eq(BlogEntity::getId,entity.getId()));
    }

    @Override
    public Page<BlogEntity> pageMyBin(PageBlogDto dto) {
        String currentUserName = UserUtils.getCurrentUserName();
        return page(new Page<>(dto.getCurrent(), dto.getSize()), new LambdaQueryWrapper<BlogEntity>()
                .select(BlogEntity::getId, BlogEntity::getTitle, BlogEntity::getCover, BlogEntity::getIsRelease, BlogEntity::getCreateTime, BlogEntity::getWriter)
                .like(StringUtils.isNotBlank(dto.getBlogTitle()), BlogEntity::getTitle, dto.getBlogTitle())
                .eq(BlogEntity::getWriter,currentUserName)
                .eq(BlogEntity::getDealFlag,1));
    }

    @Override
    public void deleteBlog(Integer id) {
        removeById(id);
        blogImageService.list(new LambdaQueryWrapper<BlogImageEntity>()
                .eq(BlogImageEntity::getBlogId,id))
                .forEach(item -> {
                    try {
                        fileCenterFeign.delete(item.getImageName());
                    }catch (Exception e){
                        log.error("删除图片失败：{}",e);
                        return;
                    }
                    blogImageService.removeById(item.getId());
                });
    }


}
